import { ElMessage } from 'element-plus'
import myCrypto from "@/utils/crypto.js"
import { getToken } from "@/utils/auth.js"
import { loadStore } from '@/store/index.js'



// const requestSalt = runtimeConfig.public.requestSalt
// 获取环境变量

let env = process.dev ? 'development' : 'production'
// console.log('env:', env)
let apiBase = 'http://localhost:7008'
if (env === 'development') {
  apiBase = 'http://localhost:7008'
} else if (env === 'production') {
  // let host = window.location.host
  // apiBase = (location.protocol || 'https') + '//s' + (host || 'address.dizhi666.com')
  apiBase = 'https://sggwork.moyutime.cn'
}

export function request(url, obj = {}) {
  let token = getToken()
  return new Promise(async (resolve, reject) => {
    url = url.includes('http') ? url : apiBase + url
    let queryObj = obj.query || obj.params || {}
    let method = (obj.method && obj.method.toUpperCase()) || 'GET'
    let queryBody = obj.body

    if(!queryObj.appName){
      queryObj.appName = '49ma'
    }
    
    if (queryBody) {
      queryBody.appName = '49ma'
      let sign = myCrypto.encrypt(queryBody)
      queryBody.sign = sign
    }
    // let sign = AES.encrypt(JSON.stringify(obj.query), requestSalt)

    let defaultHeaders = {}
    if (token) {
      token = token.trim()
      defaultHeaders.Authorization = token
    }

    let headers = Object.assign({}, obj.headers, defaultHeaders)
    try {
      $fetch(url, {
        method: method,
        query: queryObj,
        headers: headers,
        body: queryBody || null,
        onRequestError({ error }) {
          // Handle the request errors
          // console.log('onRequestError error:', error)
          reject(error)
          ElMessage.closeAll()
          // ElMessage.error(JSON.stringify(error))
        },
        onResponse({ response }) {
          // console.log('onResponse:', response)
        
          let data = response._data
          if (data && data.code === 0) {
            resolve(data.data)
          } else {
            console.error('response:', response)
            // console.log('onResponse code!==1 data:', data)
            ElMessage.closeAll()
            let msg = data && (data.message || data.msg || JSON.stringify(data))
            if (data.code === -1) {
              ElMessage.error(msg)
            } else {
              msg = msg ? msg : '请刷新重试'
              ElMessage({
                type: 'error',
                message: msg,
                duration: 5000
              })
            }

            // window.reload()
            reject(null)
          }
        }
      }).catch((error) => {
        console.log('fetch error:', error)
        // ElMessage({
        //   type: 'error',
        //   message: error
        // })
      })
    } catch (error) {
      console.log('error: ', error)
      reject(error)
    }
  })
}
